package com.bear.atlassianmcp.jira.service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * JQL查询构建器
 * 提供常用的JQL查询构建方法
 */
public class JqlBuilder {

    private StringBuilder jql;

    public JqlBuilder() {
        this.jql = new StringBuilder();
    }

    /**
     * 创建新的JQL构建器
     */
    public static JqlBuilder create() {
        return new JqlBuilder();
    }

    /**
     * 添加项目条件
     */
    public JqlBuilder project(String projectKey) {
        addCondition("project = " + quote(projectKey));
        return this;
    }

    /**
     * 添加经办人条件
     */
    public JqlBuilder assignee(String assignee) {
        if ("currentUser()".equals(assignee)) {
            addCondition("assignee = currentUser()");
        } else {
            addCondition("assignee = " + quote(assignee));
        }
        return this;
    }

    /**
     * 添加状态条件
     */
    public JqlBuilder status(String status) {
        addCondition("status = " + quote(status));
        return this;
    }

    /**
     * 添加Issue类型条件
     */
    public JqlBuilder issueType(String issueType) {
        addCondition("issuetype = " + quote(issueType));
        return this;
    }

    /**
     * 添加优先级条件
     */
    public JqlBuilder priority(String priority) {
        addCondition("priority = " + quote(priority));
        return this;
    }

    /**
     * 添加创建时间条件（大于等于指定天数前）
     */
    public JqlBuilder createdAfterDays(int days) {
        addCondition("created >= -" + days + "d");
        return this;
    }

    /**
     * 添加更新时间条件（大于等于指定天数前）
     */
    public JqlBuilder updatedAfterDays(int days) {
        addCondition("updated >= -" + days + "d");
        return this;
    }

    /**
     * 添加文本搜索条件
     */
    public JqlBuilder textSearch(String text) {
        addCondition("text ~ " + quote(text));
        return this;
    }

    /**
     * 添加标题搜索条件
     */
    public JqlBuilder summaryContains(String text) {
        addCondition("summary ~ " + quote(text));
        return this;
    }

    /**
     * 添加描述搜索条件
     */
    public JqlBuilder descriptionContains(String text) {
        addCondition("description ~ " + quote(text));
        return this;
    }

    /**
     * 添加AND条件
     */
    public JqlBuilder and() {
        if (jql.length() > 0) {
            jql.append(" AND ");
        }
        return this;
    }

    /**
     * 添加OR条件
     */
    public JqlBuilder or() {
        if (jql.length() > 0) {
            jql.append(" OR ");
        }
        return this;
    }

    /**
     * 添加排序
     */
    public JqlBuilder orderBy(String field, String direction) {
        jql.append(" ORDER BY ").append(field).append(" ").append(direction.toUpperCase());
        return this;
    }

    /**
     * 按创建时间降序排序
     */
    public JqlBuilder orderByCreatedDesc() {
        return orderBy("created", "DESC");
    }

    /**
     * 按更新时间降序排序
     */
    public JqlBuilder orderByUpdatedDesc() {
        return orderBy("updated", "DESC");
    }

    /**
     * 按优先级降序排序
     */
    public JqlBuilder orderByPriorityDesc() {
        return orderBy("priority", "DESC");
    }

    /**
     * 构建最终的JQL字符串
     */
    public String build() {
        return jql.toString().trim();
    }

    /**
     * 添加条件（内部方法）
     */
    private void addCondition(String condition) {
        if (jql.length() > 0 && !jql.toString().endsWith(" AND ") && !jql.toString().endsWith(" OR ")) {
            jql.append(" AND ");
        }
        jql.append(condition);
    }

    /**
     * 为字符串添加引号
     */
    private String quote(String value) {
        if (value.contains(" ") || value.contains("'") || value.contains("\"")) {
            return "\"" + value.replace("\"", "\\\"") + "\"";
        }
        return value;
    }

    // 常用的预定义查询
    
    /**
     * 获取当前用户的Issues
     */
    public static String getMyIssues() {
        return create()
            .assignee("currentUser()")
            .orderByUpdatedDesc()
            .build();
    }

    /**
     * 获取最近N天更新的Issues
     */
    public static String getRecentIssues(int days) {
        return create()
            .updatedAfterDays(days)
            .orderByUpdatedDesc()
            .build();
    }

    /**
     * 获取项目的Issues
     */
    public static String getProjectIssues(String projectKey) {
        return create()
            .project(projectKey)
            .orderByCreatedDesc()
            .build();
    }

    /**
     * 获取项目中指定状态的Issues
     */
    public static String getProjectIssuesByStatus(String projectKey, String status) {
        return create()
            .project(projectKey)
            .status(status)
            .orderByUpdatedDesc()
            .build();
    }

    /**
     * 搜索包含指定文本的Issues
     */
    public static String searchByText(String text) {
        return create()
            .textSearch(text)
            .orderByUpdatedDesc()
            .build();
    }
}
